package org.dtrd.modules.shop.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.pay.PayConstant;
import org.dtrd.modules.organization.entity.po.DtrdEntRdOrganization;
import org.dtrd.modules.shop.entity.bean.*;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdOrder;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdOrderJoinAddress;
import org.dtrd.modules.shop.entity.po.DtrdEntShcRdOrderRefund;
import org.dtrd.modules.shop.mapper.DtrdEntShcRdOrderRefundMapper;
import org.dtrd.modules.shop.service.IDtrdEntShcRdOrderRefundService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 商城订单退款表 服务实现类
 * </p>
 *
 * @author sun
 * @since 2022-07-25
 */
@Slf4j
@DS("multi-datasource1")
@Service
public class DtrdEntShcRdOrderRefundServiceImpl extends ServiceImpl<DtrdEntShcRdOrderRefundMapper, DtrdEntShcRdOrderRefund> implements IDtrdEntShcRdOrderRefundService {

    @Autowired
    private DtrdEntShcRdOrderServiceImpl orderService;

    @Override
    public List<OrderRefundListInfo> getOrderRefundList(OrderRefundListRequest request) {
        LambdaQueryWrapper<DtrdEntShcRdOrderRefund> queryWrapper = baseQueryWrapper();
        List<DtrdEntShcRdOrderRefund> poList = list(queryWrapper);
        List<OrderRefundListInfo> dtoList = new ArrayList<>(poList.size());
        if (!poList.isEmpty()) {
            dtoList = poList.stream().map(OrderRefundListInfo::new).collect(Collectors.toList());
        }
        return dtoList;
    }

    @Override
    public IPage<OrderRefundListInfo> pageOrderRefund(OrderRefundPageRequest request) {
        LambdaQueryWrapper<DtrdEntShcRdOrderRefund> queryWrapper = baseQueryWrapper();
        IPage<DtrdEntShcRdOrderRefund> page = new Page<>(request.getPageNum(), request.getPageSize());
        page = this.page(page, queryWrapper);
        return page.convert(OrderRefundListInfo::new);
    }

    @Override
    public OrderRefundDetail getOrderRefund(Integer dataId) {
        DtrdEntShcRdOrderRefund dtrdEntShcRdOrderRefund = getById(dataId);
        return Optional.ofNullable(dtrdEntShcRdOrderRefund)
                        .map(po -> new OrderRefundDetail().parseFromPo(po))
                        .orElse(null);
    }

    @Override
    public OrderRefundDetail getOrderRefundByOrderId(String orderId) {
        LambdaQueryWrapper<DtrdEntShcRdOrderRefund> queryWrapper = baseQueryWrapper();
        queryWrapper.eq(DtrdEntShcRdOrderRefund::getRefundOrderId, orderId);

        DtrdEntShcRdOrderRefund dtrdEntShcRdOrderRefund = getOne(queryWrapper);
        return Optional.ofNullable(dtrdEntShcRdOrderRefund)
//                .map(po -> new OrderRefundDetail().parseFromPo(po))
                .map(po -> {
                    OrderRefundDetail orderRefundDetail = new OrderRefundDetail().parseFromPo(po);
                    if (po.getRefundOrderStatus() != null) {
                        orderRefundDetail.setRefundOrderStatusText(PayConstant.OrderStatus.valueOf(po.getRefundOrderStatus()).getName());
                    }
                    return orderRefundDetail;
                })
                .orElse(null);
    }

    @Override
    public Result<?> saveOrUpdateOrderRefund(OrderRefundDetail dto) {
        if (dto.getRefundOrderId() == null) {
            return Result.error("参数错误");
        }


        log.info("========"+dto.getRefundOrderId());
        DtrdEntShcRdOrder dtrdEntShcRdOrder = orderService.getById(dto.getRefundOrderId());
//        LambdaQueryWrapper<DtrdEntShcRdOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
//        orderQueryWrapper.eq(DtrdEntShcRdOrder::getDataId, dto.getRefundOrderId());
//        DtrdEntShcRdOrder dtrdEntShcRdOrder = orderService.getOne(orderQueryWrapper);
        if (dtrdEntShcRdOrder == null || !Objects.equals(dtrdEntShcRdOrder.getOrderInfoUserid(), dto.getRefundPatientId())) {
            return Result.error("数据异常");
        }

        LambdaQueryWrapper<DtrdEntShcRdOrderRefund> queryWrapper = baseQueryWrapper();
        queryWrapper.eq(DtrdEntShcRdOrderRefund::getRefundOrderId, dto.getRefundOrderId());
        queryWrapper.ne(DtrdEntShcRdOrderRefund::getRefundStatus, 2);
        DtrdEntShcRdOrderRefund orderRefund = getOne(queryWrapper);
        if (orderRefund != null) {
            return Result.error("该订单已经申请过退款，请勿重复操作!");
        }

        DtrdEntShcRdOrderRefund dtrdEntShcRdOrderRefund = new DtrdEntShcRdOrderRefund();
        if(dto.getDataId() == null){
            dtrdEntShcRdOrderRefund = dtrdEntShcRdOrderRefund.init();
        }
        dtrdEntShcRdOrderRefund.parseFromDto(dto);
        boolean saveRefundStatus = save(dtrdEntShcRdOrderRefund);

        if (!saveRefundStatus) {
            return Result.error("退款申请操作失败");
        }

        // 修改订单状态
        dtrdEntShcRdOrder.setOrderInfoOrderstatus(PayConstant.OrderStatus.WAIT_REFUND.getType());
        return orderService.updateById(dtrdEntShcRdOrder) ? Result.OK() : Result.error("操作失败");
    }

    @Override
    public boolean removeOrderRefund(Integer dataId) {
        return removeById(dataId);
    }

    @Override
    public boolean orderRefundVerify(OrderRefundVerifyRequest verifyRequest) {
        DtrdEntShcRdOrderRefund orderRefund = getById(verifyRequest.getDataId());
        orderRefund.setRefundStatus(verifyRequest.getStatus());
        orderRefund.setRefundApproveTime(DateUtils.getDate());
        boolean updateRefund = updateById(orderRefund);
        if (updateRefund) {
            DtrdEntShcRdOrder dtrdEntShcRdOrder = orderService.getById(orderRefund.getRefundOrderId());
            if (verifyRequest.getStatus() == 1) {
                dtrdEntShcRdOrder.setOrderInfoOrderstatus(PayConstant.OrderStatus.IS_REFUND.getType());
            } else {
                dtrdEntShcRdOrder.setOrderInfoOrderstatus(PayConstant.OrderStatus.REJECT_REFUND.getType());
            }
            return orderService.updateById(dtrdEntShcRdOrder);
        }
        return false;
    }

    private LambdaQueryWrapper<DtrdEntShcRdOrderRefund> baseQueryWrapper() {
        return Wrappers.lambdaQuery(DtrdEntShcRdOrderRefund.class)
                        .eq(DtrdEntShcRdOrderRefund::getIsDel, 0);
    }

    private LambdaUpdateWrapper<DtrdEntShcRdOrderRefund> baseUpdateWrapper() {
        return Wrappers.lambdaUpdate(DtrdEntShcRdOrderRefund.class)
                        .eq(DtrdEntShcRdOrderRefund::getIsDel, 0);
    }
}
